/*
 * Copyright (c) 2006 Sun Microsystems, Inc.  All rights reserved.  U.S.
 * Government Rights - Commercial software.  Government users are subject
 * to the Sun Microsystems, Inc. standard license agreement and
 * applicable provisions of the FAR and its supplements.  Use is subject
 * to license terms.
 *
 * This distribution may include materials developed by third parties.
 * Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
 * or registered trademarks of Sun Microsystems, Inc. in the U.S. and
 * other countries.
 *
 * Copyright (c) 2006 Sun Microsystems, Inc. Tous droits reserves.
 *
 * Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
 * commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
 * licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
 * en vigueur de la FAR (Federal Acquisition Regulations) et des
 * supplements a celles-ci.  Distribue par des licences qui en
 * restreignent l'utilisation.
 *
 * Cette distribution peut comprendre des composants developpes par des
 * tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
 * sont des marques de fabrique ou des marques deposees de Sun
 * Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
 */


package database;

import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import BCrypt.BCrypt;


//import exception.*;
//import cart.*;

// The instance of BookDBAO gets created when the application
// is deployed. It maintains the Connection object to the
// database. The Connection object is created from DataSource
// object, which is retrieved through JNDI.
// For more information on DataSource, please see
// http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.html.
public class UserDBAO extends User{
	
    Connection con;
    private boolean conFree = true;
    
    public UserDBAO(String username)
    {
    	super(username);
    }
    
    
    public UserDBAO() throws Exception {
        try {
        	
        	DB db = new DB();
        	con = db.getConnection();
            
        } catch (Exception ex) {
            System.out.println("Exception in BookDBAO: " + ex);
            throw new Exception("Couldn't open connection to database: " +
                    ex.getMessage());
        }
    }
    
    public void remove() {
        try {
            con.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    protected synchronized Connection getConnection() {
        while (conFree == false) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        
        conFree = false;
        notify();
        
        return con;
    }
    
    protected synchronized void releaseConnection() {
        while (conFree == true) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        
        conFree = true;
        notify();
    }
    
    
    public boolean authenticate() {
    	boolean status = false;
        try {
            String selectStatement = "select * " + "from user where username = ?";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, username);
            
            System.out.println(prepStmt.toString());
            ResultSet rs = prepStmt.executeQuery();
            
            if (rs.next()) {
            	String hashed = rs.getString("password");
            	if(BCrypt.checkpw(password, hashed))
            	{
            		status = true;
            	}
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return status;
    }
    

    public int getAge()
    {
    	Calendar myCal = new GregorianCalendar();
    	myCal.setTime(dob);
    	
    	Calendar dobDate = myCal; // Set this to date to check
    	Calendar today = Calendar.getInstance();
    	int curYear = today.get(Calendar.YEAR);
    	int curMonth = today.get(Calendar.MONTH);
    	int curDay = today.get(Calendar.DAY_OF_MONTH);

    	int year = dobDate.get(Calendar.YEAR);
    	int month = dobDate.get(Calendar.MONTH);
    	int day = dobDate.get(Calendar.DAY_OF_MONTH);

    	int age = curYear - year;
    	if (curMonth < month || (month == curMonth && curDay < day)) {
    	    age--;
    	}	
		return age;
    }
    
    
    public boolean createUser(String username, String email, String password, String gender, java.util.Date dob) {
    	boolean success = false;
        try {
            String selectStatement = "INSERT INTO user(username,email,password,gender,dob) VALUES(?,?,?,?,?)";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, username);
            prepStmt.setString(2, email);
            
    		String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));
            prepStmt.setString(3, hashed);
            
            prepStmt.setString(4, gender);
            java.sql.Date sqlDate = new java.sql.Date(dob.getTime());
            prepStmt.setDate(5, sqlDate);
            
            System.out.println(prepStmt.toString());
            if (prepStmt.executeUpdate()==1) {
            	success = true;
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return success;
    }
    
    public boolean getUser() {
    	boolean success = false;
        try {
            String selectStatement = "select * from user where username = ?";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, username);
            
            System.out.println(prepStmt.toString());
            ResultSet rs = prepStmt.executeQuery();

            
            while (rs.next()) {
            	setUsername(rs.getString("username"));
            	setGender(rs.getString("gender"));
            	setEmail(rs.getString("email"));
            	setDob(rs.getDate("dob"));
            	setStage(rs.getInt("stage"));
            	success = true;
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return success;
    }
    
    public boolean updateUser() {
    	boolean success = false;
        try {
            String selectStatement = "UPDATE user SET email=?, gender=?, dob=?, stage=?, author=? WHERE username = ?";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, email);
            prepStmt.setString(2, gender);
            
            java.sql.Date sqlDate = new java.sql.Date(dob.getTime());
            prepStmt.setDate(3, sqlDate);
            
            prepStmt.setInt(4, stage);
            prepStmt.setInt(5, author);
            prepStmt.setString(6, username);
            
            if (prepStmt.executeUpdate()==1) {
            	success = true;
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return success;
    }
    
    public List getUsers() {
    	ArrayList list = new ArrayList();
        try {
            String selectStatement = "select * from user";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);

            ResultSet rs = prepStmt.executeQuery();
            
            while (rs.next()) {
            	User acc = new User();
            	acc.setUsername(rs.getString("username"));
            	acc.setPassword(rs.getString("password"));
            	list.add(acc);
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return list;
    	
    }
    
    public boolean checkUsername(String username) {
    	boolean exist = false;
        try {
            String selectStatement = "select * from user where username = ?";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, username);
            ResultSet rs = prepStmt.executeQuery();
            
            while (rs.next()) {
            	exist=true;
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return exist;
    }
    
    public boolean checkEmail(String email) {
    	boolean exist = false;
        try {
            String selectStatement = "select * from user where email = ?";
            getConnection();
            
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, email);
            ResultSet rs = prepStmt.executeQuery();
            
            while (rs.next()) {
            	exist=true;
            } 
            
            prepStmt.close();
            releaseConnection();
           
        } catch (SQLException ex) {
            releaseConnection();
            ex.printStackTrace();
        }
        return exist;
    }
    
    public static void main(String [] args) throws Exception{
    	UserDBAO db = new UserDBAO();
    }

}
